package cn.yi.newsys.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import cn.yi.newsys.pojo.News;
import cn.yi.newsys.service.NewsService;
import cn.yi.newsys.service.impl.NewsServiceImpl;
import cn.yi.newsys.utils.StringUtils;

public class NewsServlet extends HttpServlet{


	private static final long serialVersionUID = 1L;
	private String charEncoding = "UTF-8" ;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// 设置响应的类型
		// charset=UTF-8 用来设置字符编码格式，如不添加，则无法输出中文
		resp.setContentType("text/html;charset="+charEncoding);
		String action = req.getParameter("action") ;		
		if(action != null && action.length() > 0){
			if(action.equals("look")){
				this.lookNews(req, resp) ;
			}else if (action.equals("newsadd")){
				try {
					this.addNews(req, resp) ;
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else if(action.equals("del")){
				this.delNews(req, resp) ;
			}else{
				resp.sendRedirect("index.jsp") ;
			}
		}else{
			resp.sendRedirect("index.jsp") ;
		}
	
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// 将所有 post 请求交由 doGet 方法处理
		this.doGet(req, resp) ;
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		super.destroy();
	}

	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
	}

	@Override
	public void init(ServletConfig config) throws ServletException {
		charEncoding = config.getInitParameter("charEncoding") ;
	}
	
	/**
	 * 查阅新闻
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	private void lookNews(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter out = resp.getWriter() ;
		NewsService ns = new NewsServiceImpl() ;	
		List<News> list = ns.getAllNews() ;
		String obj = req.getParameter("id") ;
		HttpSession session = req.getSession() ;
		int num = 0 ;
		
		boolean flag = false ;
		for(News news : list){
			if(String.valueOf(news.getNid()).equals(obj)){
				flag = true ;
				break ;
			}
		}
		if(obj == null || !obj.matches("[0-9]+") || !flag){
			out.println("<script>alert('数据传输错误！');location.href='index.jsp';</script>");
		}else{		
			num = Integer.valueOf(obj) ;
			News n = ns.getNewByID(num) ;
			if(n != null){
				session.setAttribute("news", n) ;
				out.print("<script>location.href='CommentServlet?action=look'</script>");
			}
		}
		out.flush() ;
		out.close() ;		
	}

	/**
	 * 添加新闻
	 * @param req
	 * @param resp
	 * @throws Exception 
	 */
	private void addNews(HttpServletRequest request, HttpServletResponse resp)
			throws Exception {
		PrintWriter out = resp.getWriter() ;
		int row = -2;
	  	boolean isImg = false ;
	  	boolean isOnlyText = false ;
	  	News news = new News() ;
	  	// 判断是否是二进制流的提交方式
	  	boolean isMultipart = ServletFileUpload.isMultipartContent(request) ;
	  	if(isMultipart){
	  	// 创建文件上传所需的 API 实例
	  		FileItemFactory factory = new DiskFileItemFactory() ;
	  		ServletFileUpload upload = new ServletFileUpload(factory) ;			
			// 解析 request 请求，获取 FileItem 对象集合
			List<FileItem> list = upload.parseRequest(request);
			// 循环遍历集合中的数据
			for(FileItem item : list){
				// 判断对象中封装的为普通表单
				if(item.isFormField()){		// isFormField 用于判断对象中封装的表单类型  true：普通表单 false：文件表单
					String fieldName = item.getFieldName() ;
					// 赋值
					if("ntitle".equals(fieldName)){
						news.setTittle(item.getString("UTF-8"));
					}else if("nsummary".equals(fieldName)){
						news.setSummary(item.getString("UTF-8")) ;
					}else if("ntid".equals(fieldName)){
						news.setNtid(Integer.valueOf(item.getString("UTF-8"))) ;
					}else if("nauthor".equals(fieldName)){
						news.setAuthor(item.getString("UTF-8")) ;
					}else if("ncontent".equals(fieldName)){
						news.setContent(item.getString("UTF-8")) ;
					}
				}else{			// 文件表单
					// File.separator 文件分隔符
					ServletContext sc = request.getServletContext() ;
				  	String uploadPath = sc.getRealPath("/") + File.separator + "upload" ;
				  	// 如果不存在，则创建目录
				  	File uploadDir = new File(uploadPath) ;
				  	if(!uploadDir.exists()){
				  		uploadDir.mkdirs() ;
				  	}
					String name = item.getName() ;
					// 控制文件上传的类型
					if(name.endsWith(".jpg") || name.endsWith(".png") || name.endsWith(".bmp") || name.endsWith(".gif")){
						isImg = true ;
					}
					if( name != null && !"".equals(name)){
						if(isImg){
							String fileName = StringUtils.getNewName(name) ;
							// 设置新闻的图片路径
							news.setImgPath(fileName) ;
							// 远程服务器的文件地址
							File file = new File(uploadPath, fileName) ;				
							item.write(file) ;
						}
					}else{
						isOnlyText = true ;
					}
				}
			}
			
			if(isOnlyText || isImg){
				// 创建新闻业务逻辑对象
				NewsService ns = new NewsServiceImpl() ;
				// 设置新闻的发布时间
				news.setDateTime(new Date()) ;
				// 保存新闻
				row = ns.addNews(news) ;
			}
	  	}
	  	if(row == -1){
	   			out.println("<script>alert('发布失败，存在标题相同的新闻') ; location.href='newslist.jsp';</script>") ;
	   		}else if(row == 0){
	   			out.println("<script>alert('发布失败，出现未知故障，请稍后再试') ; location.href='newslist.jsp';</script>") ;
	   		}else if(row == -2){
	   			out.println("<script>alert('文件格式不正确，发布失败！') ; location.href='newslist.jsp';</script>") ;
	   		}else{
	   			out.println("<script>alert('发布成功！') ; location.href='newslist.jsp';</script>") ;
	   	}
	  
	}
	
	/**
	 * 删除新闻
	 */
	private void delNews(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter out = resp.getWriter() ;
		// 获取新闻id
		int id = Integer.valueOf(req.getParameter("newsid")) ;
		// 创建新闻业务逻辑对象
		NewsService ns = new NewsServiceImpl() ;
		boolean flag = ns.delNews(id) ;
		if(flag){
			out.print("<script>alert('删除成功！');location.href='searchnews';</script>");
		}else{
			out.print("<script>alert('删除失败！');location.href='searchnews';</script>");
		}
	}
}
